//
// Created by hy on 2018/8/18.
//

#ifndef JNI_HIMUTEX_H
#define JNI_HIMUTEX_H

#include <pthread.h>

class HiMutex {
    friend class HiSemaphore;
public:
    inline HiMutex()
    {
        pthread_mutexattr_t mta;
        pthread_mutexattr_init(&mta);
        pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&lock_, &mta);
    }
    inline ~HiMutex() { pthread_mutex_destroy(&lock_); }
    inline void lock()         { pthread_mutex_lock(&lock_); }
    inline void unlock()       { pthread_mutex_unlock(&lock_); }
    inline bool trylock()       {return 0 == pthread_mutex_trylock(&lock_);}
protected:
    pthread_mutex_t lock_;
};

class HiMutexLocker
{
public:
    inline HiMutexLocker(HiMutex *cs) { mutex_ = cs; mutex_->lock(); }
    inline ~HiMutexLocker()                    { mutex_->unlock(); }
protected:
    HiMutex *mutex_;
};

#endif //JNI_HIMUTEX_H
